package com.jymj.controller;

import com.jymj.dao.EnviorSupvsDao;
import com.jymj.dao.IllegalDao;
import com.jymj.entity.CjEntity;
import com.jymj.entity.YlEntity;
import com.jymj.entity.landmanage.*;
import com.jymj.entity.model.RjhjhpEntity;
import com.jymj.entity.zjd.ZjdCountEntity;
import com.jymj.service.CJService;
import com.jymj.service.EnviorSupvsService;
import com.jymj.service.IllegalService;
import com.jymj.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * (用一句话表示该类的作用)
 *
 * @author haosai
 */
@RestController
@RequestMapping("/illegal")
public class IllegalController extends AbstractController {
    private final String SAVE_DIR = "IllegalFile";

    @Autowired
    private IllegalService illegalService;
    @Autowired
    private IllegalDao illegalDao;
    @Autowired
    private CJService cjService;
    @Autowired
    private EnviorSupvsDao enviorSupvsDao;

    @RequestMapping("/list")
    public R queryList(@RequestBody Map<String, Object> params) {
        Integer status = null;
        Integer type = null;
        Integer limit = null;
        Integer page = null;
        String point = null;
        ArrayList list = null;
        if (params.containsKey("status") && params.get("status") != null) {
            status = Integer.valueOf(params.get("status").toString());
        }
        if (params.containsKey("type") && params.get("type") != null) {
            type = Integer.valueOf(params.get("type").toString());
        }
        if (params.get("point") != null && params.get("point") != null) {
            point = params.get("point").toString();
        }
        if (params.get("limit") != null && params.get("limit") != null) {
            limit = Integer.parseInt(params.get("limit").toString());
        }
        if (params.get("page") != null && params.get("page") != null) {
            page = Integer.parseInt(params.get("page").toString());
        }
        if (params.containsKey("codeList") && params.get("codeList") != null) {
            String codes = params.get("codeList").toString();
            String i = codes.substring(1, codes.length() - 1);
            String str = i.replace("\"", "");
            list = new ArrayList(Arrays.asList(str.split(",")));
        }
        List<IllegalEntity> illegalEntities = null;
        int total = 0;
        if (params != null && page != null && limit != null) {
            Query query = new Query(params);
            query.put("status", status);
            query.put("type", type);
            query.put("point", point);
            query.put("codeList", list);
            illegalEntities = illegalService.queryList(query);
            total = illegalService.queryTotal(query);
        } else {
            illegalEntities = illegalService.queryList(params);
            total = illegalService.queryTotal(params);
        }
        if (illegalEntities != null && illegalEntities.size() > 0) {
            for (IllegalEntity illegalEntity : illegalEntities) {
                illegalEntity.setIllegalFileEntityList(illegalDao.queryFileList(illegalEntity.getId()));
            }
        }
        if (limit == null) {
            limit = 0;
        }
        if (page == null) {
            page = 0;
        }
        PageUtils pageUtil = new PageUtils(illegalEntities, total, limit, page);
        return R.ok().put("data", pageUtil);
    }

    /*
     * 统计图
     * */
    @RequestMapping("/queryTj")
    public R queryTj(@RequestBody Map map) {
        String xzqmc = null;
        if (map == null || map.get("xzqmc") == null) {
            return R.error("无参数，删除失败");
        }
        xzqmc = map.get("xzqmc").toString();
        Integer type = null;
        if (map.containsKey("type") && map.get("type") != null) {
            type = Integer.valueOf(map.get("type").toString());
        }
        List<IllegaltjEntity> list = illegalService.queryTj(xzqmc, type);
        return R.ok().put("data", list);
    }

    @RequestMapping("/queryCount")
    public R queryCount(@RequestBody Map map) {
        Integer type = null;
        String code = null;
        if (map.containsKey("type") && map.get("type") != null) {
            type = Integer.valueOf(map.get("type").toString());
        }
        if (map.containsKey("code") && map.get("code") != null) {
            code = map.get("code").toString();
        }
        ZjdCountEntity zjdillegal = illegalService.queryIllCount(null, type, code);
        return R.ok().put("data", zjdillegal);
    }

    /*
     * 查询最近一周 一个月的信息
     * */
    @RequestMapping("/getIllegalHistoryCount")
    public R getIllegalHistoryCount(@RequestBody Map map) {
        String xzqmc = null;
        String points = null;
        Integer type = null;
        String code = null;
        if (map.containsKey("xzqmc") && map.get("xzqmc") != null) {
            xzqmc = map.get("xzqmc").toString();
        }
        if (map.containsKey("points") && map.get("points") != null) {
            points = map.get("points").toString();
        }
        if (map.containsKey("type") && map.get("type") != null) {
            type = Integer.valueOf(map.get("type").toString());
        }
        if (map.containsKey("code") && map.get("code") != null) {
            code = map.get("code").toString();
        }
        IllegalHistoryCount entity = illegalService.getIllegalHistoryCount(xzqmc, points, type, code);
        return R.ok().put("data", entity);
    }

    /*
     * 添加
     * */
    @RequestMapping("/save")
    public R save(@RequestBody IllegalEntity illegalEntity) {
        if (illegalEntity.getType() != null && illegalEntity.getType() != 3) {
            if (illegalEntity.getIds() == null || illegalEntity.getIds().length == 0) {
                return R.error("请补全资料");
            }
        }
        illegalEntity.setEnpsn(getUser().getUsername());
        IllegalEntity illegalEntity1 = illegalDao.queryByYlId(illegalEntity.getYlId());
        if (illegalEntity1 != null) {
            return R.error("已有信息");
        }
        int i = illegalService.save(illegalEntity);
        if (i > 0) {
            return R.ok();
        }
        return R.error();
    }

    /*
     * 查找位置
     * */
    @RequestMapping("/queryByPoint")
    public R queryByPoint(@RequestBody Map map) {
        String point = null;
        Integer type = null;
        if (map == null || map.get("point") == null) {
            return R.error("无参数，删除失败");
        }
        if (map != null || map.get("type") != null) {
            type = Integer.parseInt(map.get("type").toString());
        }
        point = map.get("point").toString();
        if (type != null && type == 1) {
            YlEntity ylEntities = illegalService.queryByPoint(point);
            if (ylEntities == null) {
                return R.error("该位置不在区域内，请重新选择");
            }
            IllegalEntity illegalEntity = illegalDao.queryByYlId(ylEntities.getObjectid());
            if (illegalEntity == null) {
                return R.ok().put("data", ylEntities);
            }
            illegalEntity.setYlEntity(ylEntities);
            return R.ok("该位置已有数据").put("data", illegalEntity);
        } else {
            CjEntity cjEntity = illegalService.queryCjByPoint(point);
            List<IllegalEntity> illegalEntity = illegalService.queryByLocation(point);
            if (illegalEntity.size() > 0) {
                return R.ok("该位置已有数据").put("data", illegalEntity);
            }

            //查询村庄范围

            Integer i = null;
            RjhjhpEntity rjhjhpEntity = cjService.queryCzfw(point);
            //固定点位
            PointRecordEntity pointRecordEntity = cjService.queryByPoint(point);
            Map<String, List<PjEnviorSupvsEntity>> pjEnviorSupvsList = new LinkedHashMap<>();
            if (pointRecordEntity != null) {
                //点位对应问题及图片 进行排序
                List<PjEnviorSupvsEntity> pjEnviorSupvsEntities = enviorSupvsDao.queryByGddwid(pointRecordEntity.getId());
                if (pjEnviorSupvsEntities != null || pjEnviorSupvsEntities.size() != 0) {
                    pjEnviorSupvsList =
                            pjEnviorSupvsEntities.stream()
                                    .collect(Collectors
                                            .groupingBy(PjEnviorSupvsEntity::getMonth, LinkedHashMap::new, Collectors.toList()));
                }
            }

            if (rjhjhpEntity != null) {
                i = 1;
            } else {
                i = 2;
            }
            if (cjEntity != null) {
                return R.ok().put("data", cjEntity).put("czfw", i).
                        put("point", pointRecordEntity).put("PjEnviorSupvs", pjEnviorSupvsList);
            }else if (pointRecordEntity != null){
                return R.ok().put("czfw", i).
                        put("point", pointRecordEntity).put("PjEnviorSupvs", pjEnviorSupvsList);
            }
            return R.error("该位置不在区域内，请重新选择");
        }
    }

    /*
     * 修改
     * */
    @RequestMapping("/updateStatus")
    public R updateStatus(@RequestBody IllegalEntity illegalEntity) {
        illegalEntity.setOvertime(new Date());
        if (illegalEntity.getIds() == null || illegalEntity.getIds().length == 0) {
            return R.error("请补全资料");
        }
        int i = illegalService.updateStatus(illegalEntity);
        if (i > 0) {
            return R.ok();
        }
        return R.error();
    }

    /*
     * 删除
     * */
    @RequestMapping("delete")
    public R delete(@RequestBody Map map, HttpServletRequest request) throws FileNotFoundException {
        Integer id = null;
        if (map == null || map.get("id") == null) {
            return R.error("无参数，删除失败");
        }
        id = Integer.parseInt(map.get("id").toString());
        int i = illegalService.delete(id);
        File genPath = new File(ResourceUtils.getURL("jar:").getPath());
        File savePath1 = new File(genPath.getAbsolutePath().replace("jar:", "fileupload"));
        List<IllegalFileEntity> illegalFileEntities = illegalService.queryFiles(id);
        for (IllegalFileEntity illegalFileEntity : illegalFileEntities) {
            String savePath = savePath1 + File.separator + illegalFileEntity.getPath();
            //删除文件
            File file = new File(savePath);
            file.delete();
        }
        if (i > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 上传文件 图片
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public Map uploadFile(HttpServletRequest request) throws FileNotFoundException {
        Map<String, Object> map = new HashMap();
        //资料表实体
        IllegalFileEntity illegalFileEntity = new IllegalFileEntity();
        // 获取根目录的绝对路径
        File genPath = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!genPath.exists()) {
            genPath = new File("");
        }
        //在开发测试模式时，得到地址为：{项目跟目录}/target/progress/
        //在打成jar正式发布时，得到的地址为:{发布jar包目录}/progress/
        File savePath = new File(genPath.getAbsolutePath(), "fileupload" + File.separator + SAVE_DIR);
        File savePath1 = new File(genPath.getAbsolutePath(), "fileupload");
        if (!savePath.exists()) {
            savePath.mkdirs();
            System.out.println("文件路径为：+" + savePath.getAbsolutePath());
        }
        //if (multipartResolver.isMultipart(request)) {
        //转换成多部分request
        MultipartHttpServletRequest multiRequest = null;
        if (request instanceof MultipartHttpServletRequest) {
            multiRequest = (MultipartHttpServletRequest) (request);
        } else {
            return R.error("文件不能为空！");
        }
        //取得request中的所有文件名
        Iterator<String> iter = multiRequest.getFileNames();
        while (iter.hasNext()) {
            //取得上传文件
            MultipartFile file = multiRequest.getFile(iter.next());
            if (file != null) {
                //取得当前上传文件的文件名称
                String myFileName = file.getOriginalFilename();
                //如果名称不为“”,说明该文件存在，否则说明该文件不存在
                if (!"".equals(myFileName.trim())) {
                    //重命名上传后的文件名
                    String fileName = file.getOriginalFilename();
                    //System.out.println(savePath + "\\" + fileName);
                    illegalFileEntity.setFilename(fileName);
                    String ext = fileName.substring(fileName.indexOf("."));
                    TimeString st = new TimeString();
                    illegalFileEntity.setPath(SAVE_DIR + File.separator + st.getTimeString() + ext);
                    illegalService.saveFile(illegalFileEntity);
                    //上传路径
                    String path = savePath1 + File.separator + illegalFileEntity.getPath();
                    File localFile = new File(path);
                    try {
                        file.transferTo(localFile);
                    } catch (IOException e) {
                        return R.error("上传失败").put("code", 500);
                    }
                }
            } else {
                return R.error("文件不能为空！");
            }
        }
        //}
        map.put("data", illegalFileEntity);
        map.put("msg", "上传成功！");
        map.put("code", 0);
        return map;

    }

    /*
     * 删除文件 图片
     * */
    @RequestMapping("/deleteFileUrl")
    public R deleteFileUrl(@RequestBody Map map, HttpServletRequest request) throws FileNotFoundException {
        File genPath = new File(ResourceUtils.getURL("jar:").getPath());
        File savePath1 = new File(genPath.getAbsolutePath().replace("jar:", "fileupload"));
        String url = null;
        if (map == null || map.get("url") == null) {
            return R.error("无参数，删除失败");
        }
        url = map.get("url").toString();
        // 构造文件存放的路径
        String savePath = savePath1 + File.separator + url;
        //删除文件
        File file = new File(savePath);
        file.delete();
        //删除数据库图片记录
        illegalDao.deleteFile(url);
        return R.ok("删除成功！");
    }
}
